package com.tjd.uploaddemo.utils.fileutils;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Auther: 田金东
 * @Date: 12/12/0012
 **/
public class FileChunkInfo {
    private String basePath;//临时文件夹路径
    private String name;//上传文件名
    private String surfix;//后缀名
    private int totalChuanks;//总分片数
    private List<FileChunk> chunks;

    public FileChunkInfo(String name, String basePath, int totalChuanks) {
        this.name = name;
        this.basePath = basePath;
        this.totalChuanks = totalChuanks;
        if (name.lastIndexOf(".") != -1) {
            this.surfix = name.substring(name.lastIndexOf("."));
        } else {
            this.surfix = "";
        }
        this.chunks = new ArrayList<>(totalChuanks);
    }

    public int getChunkNum() {
        synchronized (chunks) {
            return chunks.size();
        }
    }

    /**
     * 分片上传是否完成
     *
     * @return
     */
    public boolean isFinished() {
        synchronized (chunks) {
            return this.chunks.size() == totalChuanks;
        }
    }

    public void addFileChunk(FileChunk chunk) {
        synchronized (chunks) {
            chunks.add(chunk);
        }
    }

    public String getBasePath() {
        return basePath;
    }

    /**
     * 合并文件
     */
    public void mergeFile() throws IOException {
        if (this.totalChuanks <= 1) {
            return;
        }
        Collections.sort(this.chunks);
        InputStream input1 = chunks.get(0).getInputStream();
        InputStream input2 = chunks.get(1).getInputStream();
        SequenceInputStream s = new SequenceInputStream(input1, input2);
        for (int i = 2; i < this.totalChuanks; i++) {
            s = new SequenceInputStream(s, chunks.get(i).getInputStream());
        }
        byte[] buffer = new byte[1024];
        int len = 0;
        FileOutputStream output = new FileOutputStream(this.basePath + name);
        while ((len = s.read(buffer)) != -1) {
            output.write(buffer, 0, len);
            output.flush();
        }
        output.close();
        deleteTmpFile();
    }

    /**
     * 删除所有临时文件
     */
    public void deleteTmpFile() {
        for (FileChunk chunk : this.chunks) {
            chunk.deleteFile();
        }
    }

    public String getSurfix() {
        return surfix;
    }
}
